//
//  FJKWebView.m
//  测试
//
//  Created by 刘帆 on 16/6/17.
//  Copyright © 2016年 FangGeek. All rights reserved.
//

#import "FJKWebView.h"
#import "WXApiRequestHandler.h"
#import "ZLPhotoActionSheet.h"
#import "SAShareView.h"
#import "WXApiManager.h"
#import "ChatViewController.h"
//#import "FJKJSBridge.h"
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#define isiOS8 [[[UIDevice currentDevice] systemVersion] floatValue]>=8.0
static void *FJKWebBrowserContext = &FJKWebBrowserContext;


@interface FJKWebView ()<UIAlertViewDelegate,WKScriptMessageHandler,WXApiManagerDelegate>
@property (nonatomic, strong) NSTimer *fakeProgressTimer;
@property (nonatomic, assign) BOOL uiWebViewIsLoading;
@property (nonatomic, strong) NSURL *uiWebViewCurrentURL;
@property (nonatomic, strong) NSURL *URLToLaunchWithPermission;
@property (nonatomic, strong) UIAlertView *externalAppPermissionAlertView;

//@property (nonatomic, strong) FJKJSBridge *jsBridge;   //JS桥

@end

@implementation FJKWebView

#pragma mark --Initializers
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        if(isiOS8)
        {
            ////创建一个WKWebView的配置对象
            WKWebViewConfiguration *configur = [[WKWebViewConfiguration alloc] init];
            
            //设置configur对象的preferences属性的信息
            WKPreferences *preferences = [[WKPreferences alloc] init];
            configur.preferences = preferences;
            
            //是否允许与js进行交互，默认是YES的，如果设置为NO，js的代码就不起作用了
            preferences.javaScriptEnabled = YES;
            WKUserContentController *userContentController = [[WKUserContentController alloc]init];
            [userContentController addScriptMessageHandler:self name:@"wxShare"];
            [userContentController addScriptMessageHandler:self name:@"onRefreshPage"];
            [userContentController addScriptMessageHandler:self name:@"onOpenAlbum"];
            [userContentController addScriptMessageHandler:self name:@"showShare"];
            [userContentController addScriptMessageHandler:self name:@"onOpenChat"];
            
            configur.userContentController = userContentController;
            
            self.wkWebView = [[WKWebView alloc] initWithFrame:frame configuration:configur];
        }
        else
        {
            self.uiWebView = [[UIWebView alloc] init];
        }
        
        
        self.backgroundColor = [UIColor whiteColor];
        
        if(self.wkWebView) {
            
            [self.wkWebView setFrame:frame];
            [self.wkWebView setNavigationDelegate:self];
            [self.wkWebView setUIDelegate:self];
            [self.wkWebView setMultipleTouchEnabled:YES];
            [self.wkWebView setAutoresizesSubviews:YES];
            [self.wkWebView.scrollView setAlwaysBounceVertical:YES];
            [self addSubview:self.wkWebView];
            [self.wkWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
            [self.wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:FJKWebBrowserContext];
        }
        else  {
            [self.uiWebView setFrame:frame];
            //            [self.uiWebView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
            [self.uiWebView setDelegate:self];
            [self.uiWebView setMultipleTouchEnabled:YES];
            [self.uiWebView setAutoresizesSubviews:YES];
            [self.uiWebView setScalesPageToFit:YES];
            [self.uiWebView.scrollView setAlwaysBounceVertical:YES];
            [self addSubview:self.uiWebView];
        }
        
        self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        [self.progressView setTrackTintColor:[UIColor colorWithWhite:1.0f alpha:0.0f]];
        [self.progressView setFrame:CGRectMake(0, 0, self.frame.size.width, self.progressView.frame.size.height)];
        
        //设置进度条颜色
        [self setTintColor:SAHEXRGB(0xE53546)];
        [self addSubview:self.progressView];
        
        //创建JS桥
        //        self.jsBridge = [[FJKJSBridge alloc] initWithWKWebView:self.wkWebView];
    }
    return self;
}

#pragma mark - Public Interface
- (void)loadRequest:(NSURLRequest *)request {
    if(self.wkWebView)
    {
        [self.wkWebView loadRequest:request];
    }
    else
    {
        [self.uiWebView loadRequest:request];
    }
}
-(NSMutableURLRequest *)setCookie:(NSURL *)url
{
    
    NSMutableURLRequest * requestM = [NSMutableURLRequest requestWithURL:url];
    
    return requestM;
    
}
- (void)loadURL:(NSURL *)URL {
    [self loadRequest:[NSURLRequest requestWithURL:URL]];
}

- (void)loadURLString:(NSString *)URLString {
    NSURL *URL = [NSURL URLWithString:URLString];
    [self loadURL:URL];
}

- (void)loadHTMLString:(NSString *)HTMLString {
    if(self.wkWebView) {
        [self.wkWebView loadHTMLString:HTMLString baseURL:nil];
    }
    else if(self.uiWebView) {
        [self.uiWebView loadHTMLString:HTMLString baseURL:nil];
    }
}



- (void)setTintColor:(UIColor *)tintColor {
    _tintColor = tintColor;
    [self.progressView setTintColor:tintColor];
}

- (void)setBarTintColor:(UIColor *)barTintColor {
    _barTintColor = barTintColor;
}



#pragma mark - UIWebViewDelegate

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    if(webView == self.uiWebView) {
        [self.delegate fjkwebViewDidStartLoad:self];
        
    }
}

//监视请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    if(webView == self.uiWebView) {
        
        if(![self externalAppRequiredToOpenURL:request.URL]) {
            self.uiWebViewCurrentURL = request.URL;
            self.uiWebViewIsLoading = YES;
            
            [self fakeProgressViewStartLoading];
            
            
            //back delegate
            [self.delegate fjkwebView:self shouldStartLoadWithURL:request.URL];
            return YES;
        }
        else {
            [self launchExternalAppWithURL:request.URL];
            return NO;
        }
    }
    return NO;
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    
    if(webView == self.uiWebView) {
        if(!self.uiWebView.isLoading) {
            self.uiWebViewIsLoading = NO;
            
            [self fakeProgressBarStopLoading];
        }
        self.titleLabel = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        //back delegate
        [self.delegate fjkwebView:self didFinishLoadingURL:self.uiWebView.request.URL];
        
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    
    if(webView == self.uiWebView) {
        if(!self.uiWebView.isLoading) {
            self.uiWebViewIsLoading = NO;
            
            [self fakeProgressBarStopLoading];
        }
        
        //back delegate
        [self.delegate fjkwebView:self didFailToLoadURL:self.uiWebView.request.URL error:error];
    }
}


#pragma mark - WKNavigationDelegate


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    if(webView == self.wkWebView) {
 
        if ([self.delegate respondsToSelector:@selector(fjkwebViewDidStartLoad:)])
        {
            //back delegate
            [self.delegate fjkwebViewDidStartLoad:self];
        }
        
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    if(webView == self.wkWebView) {
        if ([self.delegate respondsToSelector:@selector(fjkwebView:didFinishLoadingURL:)])
        {
            //back delegate
            [self.delegate fjkwebView:self didFinishLoadingURL:self.wkWebView.URL];
        }
        
    }
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
      withError:(NSError *)error {
    if(webView == self.wkWebView) {
        //back delegate
        if ([self.delegate respondsToSelector:@selector(fjkwebView:didFailToLoadURL:error:)])
        {
            [self.delegate fjkwebView:self didFailToLoadURL:self.wkWebView.URL error:error];
        }
        
        
    }
    
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation
      withError:(NSError *)error {
    if(webView == self.wkWebView) {
        //back delegate
        if ([self.delegate respondsToSelector:@selector(fjkwebView:didFailToLoadURL:error:)])
        {
            [self.delegate fjkwebView:self didFailToLoadURL:self.wkWebView.URL error:error];
        }
        
    }
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if(webView == self.wkWebView) {
        NSURL *URL = navigationAction.request.URL;
        if(![self externalAppRequiredToOpenURL:URL]) {
            if(!navigationAction.targetFrame) {
                [self loadURL:URL];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
            UIApplication *app = [UIApplication sharedApplication];
            if ([URL.scheme isEqualToString:@"tel"])
            {
                if ([app canOpenURL:URL])
                {
                    [app openURL:URL];
                    decisionHandler(WKNavigationActionPolicyCancel);
                    return;
                }
            }
            [self callback_webViewShouldStartLoadWithRequest:navigationAction.request navigationType:navigationAction.navigationType];
            
        }
        else if([[UIApplication sharedApplication] canOpenURL:URL]) {
            [self launchExternalAppWithURL:URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
    
}

-(BOOL)callback_webViewShouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(NSInteger)navigationType
{
    //back delegate
    if ([self.delegate respondsToSelector:@selector(fjkwebView:shouldStartLoadWithURL:)])
    {
        [self.delegate fjkwebView:self shouldStartLoadWithURL:request.URL];
    }
    
    return YES;
}


#pragma mark - WKUIDelegate

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
#pragma mark - Estimated Progress KVO (WKWebView)

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }else if ([keyPath isEqualToString:@"title"])
    {
        if (object == self.wkWebView)
        {
            
            self.ViewController.title = self.wkWebView.title;
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
            
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - Fake Progress Bar Control (UIWebView)

- (void)fakeProgressViewStartLoading {
    [self.progressView setProgress:0.0f animated:NO];
    [self.progressView setAlpha:1.0f];
    
    if(!self.fakeProgressTimer) {
        self.fakeProgressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(fakeProgressTimerDidFire:) userInfo:nil repeats:YES];
    }
}

- (void)fakeProgressBarStopLoading {
    if(self.fakeProgressTimer) {
        [self.fakeProgressTimer invalidate];
    }
    
    if(self.progressView) {
        [self.progressView setProgress:1.0f animated:YES];
        [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
            [self.progressView setAlpha:0.0f];
        } completion:^(BOOL finished) {
            [self.progressView setProgress:0.0f animated:NO];
        }];
    }
}

- (void)fakeProgressTimerDidFire:(id)sender {
    CGFloat increment = 0.005/(self.progressView.progress + 0.2);
    if([self.uiWebView isLoading]) {
        CGFloat progress = (self.progressView.progress < 0.75f) ? self.progressView.progress + increment : self.progressView.progress + 0.0005;
        if(self.progressView.progress < 0.95) {
            [self.progressView setProgress:progress animated:YES];
        }
    }
}

#pragma mark - WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"wxShare"])
    {
        NSData *data = [message.body dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *tempDictQueryDiamond = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        [WXApiRequestHandler sendLinkURL: [NSString stringWithFormat:@"%@%@%@",tempDictQueryDiamond[@"link"],[tempDictQueryDiamond[@"link"] contains:@"?"]?@"&phone=":@"?phone=",[SAUserDefaults objectForKey:@"SAPhone"]]
                                 TagName:@"门店助手"
                                   Title:tempDictQueryDiamond[@"title"]
                             Description:tempDictQueryDiamond[@"desc"]
                              ThumbImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tempDictQueryDiamond[@"imgUrl"]]]]
                                 InScene:WXSceneSession];
    }
    else if ([message.name isEqualToString:@"onRefreshPage"])
    {
        [MBProgressHUD showMessage:@"请稍候..."];
        [SAHttpApi requestGetHTTPURLWithNumber:[[SAUserDefaults objectForKey:[SAUserInfoManager sharedSAUserInfoManager].model.shopId] integerValue] != 0 ?[NSString stringWithFormat:@"%@",[SAUserDefaults objectForKey:[SAUserInfoManager sharedSAUserInfoManager].model.shopId]]:([[SAUserInfoManager sharedSAUserInfoManager].model.identityCollect isEqualToString:@"2"]?@"1":@"2") WithEmpId:[SAUserInfoManager sharedSAUserInfoManager].model._id WithAppTo:[SAUserInfoManager sharedSAUserInfoManager].model.identityCollect WithComeBack:^(NSDictionary *object, NSError *error) {
            if (!error)
            {
                
                if ([object[@"status"] integerValue] == 1)
                {
                    [MBProgressHUD hideHUD];
                    [self.wkWebView.backForwardList performSelector:NSSelectorFromString(@"_removeAllItems")];
                    [self loadURLString:object[@"content"]];
                }
                else
                {
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showError:object[@"msg"]];
                    
                }
            }
            else
            {
                [MBProgressHUD hideHUD];
                [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
            }
        }];
        
        
        
    }
    else if ([message.name isEqualToString:@"onOpenAlbum"])
    {
        ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
        //设置照片最大预览数
        actionSheet.maxPreviewCount = [message.body integerValue];
        //设置照片最大选择数
        actionSheet.maxSelectCount = [message.body integerValue];
        actionSheet.sender = self.ViewController;
        actionSheet.allowMixSelect = NO;
        actionSheet.allowSelectVideo = NO;
        actionSheet.allowEditImage = NO;
        actionSheet.allowEditVideo = NO;
        actionSheet.allowTakePhotoInLibrary = NO;
        actionSheet.allowSelectOriginal = NO;
        actionSheet.navBarColor = [UIColor whiteColor];
        actionSheet.navTitleColor = [UIColor blackColor];
        
        SAWeakSelf
        [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
            SAStrongSelf
            
            NSMutableArray *arr = [NSMutableArray array];
            
            for (UIImage *image in images)
            {
                NSData *data = UIImageJPEGRepresentation(image, 0.1);
                NSString *base64String = [NSString stringWithFormat:@"data:image/JPEG;base64,%@",[self encode_base64_data:data]];
                [arr addObject:base64String];
            }
            
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{@"data":arr}
                                                               options:0
                                                                 error:nil];
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
            jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
            jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"];
            jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
            jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\r" withString:@"\\r"];
            jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\f" withString:@"\\f"];
            jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\u2028" withString:@"\\u2028"];
            jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\u2029" withString:@"\\u2029"];
            
            [strongSelf.wkWebView evaluateJavaScript:[NSString stringWithFormat:@"callBridgeOnReceive('%@')",jsonString] completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
  
            }];
  
        }];
        
        //调用相册
        [actionSheet showPhotoLibrary];
        
    }
    else if ([message.name isEqualToString:@"showShare"])
    {
        
        self.superview.ViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share_more"] style:UIBarButtonItemStylePlain block:^(id weakSender) {
            
            NSData *data = [message.body dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *tempDictQueryDiamond = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            SAShareView *shareView = [[NSBundle mainBundle] loadNibNamed:@"SAShareView" owner:nil options:nil].lastObject;
            shareView.frame = CGRectMake(0, 0, SA_SCREEN_WIDTH, SA_SCREEN_HEIGHT);
            [shareView showAnimation];
            
            [shareView.wetchatBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
                
                [WXApiRequestHandler sendLinkURL: tempDictQueryDiamond[@"link"]
                                         TagName:@"门店助手"
                                           Title:tempDictQueryDiamond[@"title"]
                                     Description:tempDictQueryDiamond[@"desc"]
                                      ThumbImage:[[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tempDictQueryDiamond[@"imgUrl"]]]] scaleToSize:CGSizeMake(60, 60)]
                                         InScene:WXSceneSession];
            }];
            
            [shareView.timeLineBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
                
                [WXApiRequestHandler sendLinkURL: tempDictQueryDiamond[@"link"]
                                         TagName:@"门店助手"
                                           Title:tempDictQueryDiamond[@"title"]
                                     Description:tempDictQueryDiamond[@"desc"]
                                      ThumbImage:[[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tempDictQueryDiamond[@"imgUrl"]]]] scaleToSize:CGSizeMake(60, 60)]
                                         InScene:WXSceneTimeline];
            }];
            
            SAWeakObj(shareView)
            [shareView.linkBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
                SAStrongObj
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = tempDictQueryDiamond[@"link"];
                [MBProgressHUD showSuccess:@"复制成功"];
                [strongObj removeAnimation];
            }];
        }];
        

    }
    else if ([message.name isEqualToString:@"onOpenChat"])
    {
        NSData *data = [message.body dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *tempDictQueryDiamond = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        [SAHttpApi requestGetFanUserInfoWithShopId:[SAUserInfoManager sharedSAUserInfoManager].model.shopId WithHyUserId:tempDictQueryDiamond[@"head"][@"replyTo"] WithComeBack:^(NSDictionary *object, NSError *error) {
            if (!error)
            {
                ChatViewController *chatVC = [[ChatViewController alloc] init];
                chatVC.strChatterName = object[@"content"][@"wxNickName"];
                chatVC.strChatterThumb = object[@"content"][@"wxPhoto"];
                chatVC.headDict =tempDictQueryDiamond[@"head"];
                [self.ViewController.navigationController pushViewController:chatVC animated:YES];
            }
        }];
        
   
    }
    
}

#pragma mark - External App Support
- (BOOL)externalAppRequiredToOpenURL:(NSURL *)URL {
    
    //若需要限制只允许某些前缀的scheme通过请求，则取消下述注释，并在数组内添加自己需要放行的前缀
    //    NSSet *validSchemes = [NSSet setWithArray:@[@"http", @"https",@"file"]];
    //    return ![validSchemes containsObject:URL.scheme];
    
    return !URL;
}

- (void)launchExternalAppWithURL:(NSURL *)URL {
    self.URLToLaunchWithPermission = URL;
    if (![self.externalAppPermissionAlertView isVisible]) {
        [self.externalAppPermissionAlertView show];
    }
    
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if(alertView == self.externalAppPermissionAlertView) {
        if(buttonIndex != alertView.cancelButtonIndex) {
            [[UIApplication sharedApplication] openURL:self.URLToLaunchWithPermission];
        }
        self.URLToLaunchWithPermission = nil;
    }
}

#pragma mark - Dealloc

- (void)dealloc {
    [self.uiWebView setDelegate:nil];
    [self.wkWebView setNavigationDelegate:nil];
    [self.wkWebView setUIDelegate:nil];
    [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [self.wkWebView removeObserver:self forKeyPath:@"title"];
    //移除所有JS Handler
    //    [self.jsBridge removeAllScriptMessageHandler];
    
    NSLog(@"FJKWebView Dealloc");
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self.ViewController presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self.ViewController presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([alertController.textFields firstObject].text?:@"");
    }])];
    
}

-(void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([challenge previousFailureCount] == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

- (NSString *)encode_base64_data:(NSData *)data
{
    if ([data length] == 0)
    {
        return @"";
    }
    
    char *characters = malloc((([data length] + 2) / 3) * 4);
    if (characters == NULL)
    {
        return nil;
    }
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (i < [data length])
    {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < [data length])
        {
            buffer[bufferLength++] = ((char *)[data bytes])[i++];
        }
        
        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
        {
            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        }
        else
        {
            characters[length++] = '=';
        }
        
        if (bufferLength > 2)
        {
            characters[length++] = encodingTable[buffer[2] & 0x3F];
        }
        else
        {
            characters[length++] = '=';
        }
    }
    
    NSString *returnStr = [[NSString alloc] initWithBytes:characters length:length encoding:NSASCIIStringEncoding];
    free(characters);
    return returnStr;
}


@end
